package cn.tedu.demo04wy.controller;


import cn.tedu.demo04wy.entity.Commodity;
import cn.tedu.demo04wy.mapper.CommodityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/commodity/")
public class CommodityController {
    @Autowired(required = false)
    CommodityMapper commodityMapper;

    @Value("${d:/upload/photo}")
    private String dirPath;

    @RequestMapping("selectC2")
    public List<Commodity> selectC2() {
        return commodityMapper.selectC2();
    }

    @RequestMapping("selectC1")
    public List<Commodity> selectC1() {
        return commodityMapper.selectC1();
    }

    @RequestMapping("add")
    public void add(int id) {
        commodityMapper.addCount(id);
    }

    @RequestMapping("reduce")
    public void reduce(int id) {
        commodityMapper.reduceCount(id);
    }

    @RequestMapping("insert")
    public int insert(Commodity commodity, MultipartFile picFile) throws IOException {
        System.out.println("commodity = " + commodity + ", picFile = " + picFile);
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;
        //得到和日期相关的路径
        SimpleDateFormat format = new SimpleDateFormat("/YYYY/MM/dd/");
        //把当前时间按照指定的格式进行转换/2021/10/19/
        String datePath = format.format(new Date());
        //得到保存图片文件夹得路径d:/upload/vrd/2021/10/19/
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到完整的文件路径
        String filePath = dirPath + datePath + fileName;
        //保存上传图片
        picFile.transferTo(new File(filePath));
        //把图片路径添加到product对象里面
        commodity.setUrl(datePath + fileName);
        commodity.setTime(new Date());
        commodityMapper.insert(commodity);
        return 1;
    }



}
